Google API to Calculate a Distance in PHP / Mysql
I actually had a hard time finding some of the Geographic calculations to find the distance between two locations so I wanted to share them here.
If you remember ‘the old days’ of calculating a distance between two points, it was simply the hypotenuse of a triangle (A² + B² = C²).
That’s an interesting start but it doesn’t apply with Geography since the distance between lines of latitude and longitude are not an equal distance apart. As you get closer to the equator, lines of latitude get further apart. If you use some kind of simple triangulation equation, it may measure distance accurately in one location and terribly wrong in the other, because of the curvature of the Earth.
That brings up the Haversine formula, which uses trigonometry to allow for the curvature of the earth. When you’re finding the distance between 2 places on earth (as the crow flies), a straight line is really an arc. This is applicable in air flight – have you ever looked at the actual map of flights and noticed they are arched? That’s because it’s shorter to fly in an arch between two points sometimes than directly to the location.
Anyways, here’s the PHP formula for calculating the distance between two points (along with Mile vs. Kilometer conversion) rounded to two decimal places:
Distance Calculator in PHP:
Distance Calculator in MYSQL for lat long data stored in DB:
It’s also possible to use MySQL to do a calculation to find all records within a specific distance. In this example, I’m going to query MyTable to find all the records that are less than or equal to variable $distance (in Miles) to my location at $latitude and $longitude:
For Miles:
For KM:
Arjun is a Full-stack developer, who is fond of the web. Lives in Chikmagalur, Karnataka, India